package v1

import dai.core.base.MyLog
import dai.core.base.Utils
import org.lwjgl.glfw.GLFW
import org.lwjgl.glfw.GLFW.glfwWindowShouldClose

class GameApp(
    val scene:Scene,
    val window: Window,
    val camera: Camera,
    val renderer:Renderer
){
    var frameCount = 0
    var dt = 0f

    companion object{
        const val OneFrameTime:Int = 1000/60
        const val Debug = true
    }

    fun init(){
        window.init(this)
        renderer.init(this)
        camera.init(this)
        scene.init(this)
    }

    fun cleanup(){
        GLFW.glfwTerminate()
        scene.cleanup()
        renderer.cleanup()
        camera.cleanup()
        window.cleanup()
    }

    fun launch(){
        init()
        var lastMs = Utils.curMs()
        while (!glfwWindowShouldClose(window.winHandle)){
            val curMs = Utils.curMs()
            val dtMs = curMs - lastMs
            lastMs = curMs
            dt = dtMs / 1000f
            window.beginFrame()
            scene.input()
            scene.update()
            renderer.render(scene,camera)
            window.endFrame()
            frameCount++
            val frameMs = Utils.curMs() - curMs
            if (frameMs < OneFrameTime){
                Thread.sleep(OneFrameTime - frameMs)
            }
        }
        cleanup()
    }
}